package cn.heyige.backend.service.impl;

import cn.heyige.backend.entity.YaoCiDO;
import cn.heyige.backend.mapper.YaoCiMapper;
import cn.heyige.backend.service.YaoCiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Slf4j
public class YaoCiServiceImpl implements YaoCiService {
    
    private final YaoCiMapper yaoCiMapper;
    
    @Override
    public Optional<YaoCiDO> getYaoCiById(Integer id) {
        try {
            YaoCiDO yaoCi = yaoCiMapper.selectById(id);
            return yaoCi != null ? Optional.of(yaoCi) : Optional.empty();
        } catch (Exception e) {
            log.error("根据ID获取爻辞失败: {}", id, e);
            return Optional.empty();
        }
    }
    
    @Override
    public List<YaoCiDO> getYaoCiByHexagramId(Integer hexagramId) {
        try {
            return yaoCiMapper.findByHexagramId(hexagramId);
        } catch (Exception e) {
            log.error("根据卦象ID获取爻辞失败: {}", hexagramId, e);
            return List.of();
        }
    }
    
    @Override
    public YaoCiDO getYaoCiByHexagramIdAndPosition(Integer hexagramId, Integer yaoPosition) {
        try {
            return yaoCiMapper.findByHexagramIdAndYaoPosition(hexagramId, yaoPosition);
        } catch (Exception e) {
            log.error("根据卦象ID和爻位获取爻辞失败: {}, {}", hexagramId, yaoPosition, e);
            return null;
        }
    }
    
    @Override
    public List<YaoCiDO> getAllYaoCi() {
        try {
            return yaoCiMapper.selectList(null);
        } catch (Exception e) {
            log.error("获取所有爻辞失败", e);
            return List.of();
        }
    }
    
    @Override
    public YaoCiDO saveYaoCi(YaoCiDO yaoCi) {
        try {
            yaoCiMapper.insert(yaoCi);
            return yaoCi;
        } catch (Exception e) {
            log.error("保存爻辞失败: {}", yaoCi, e);
            return null;
        }
    }
    
    @Override
    public YaoCiDO updateYaoCi(YaoCiDO yaoCi) {
        try {
            yaoCiMapper.updateById(yaoCi);
            return yaoCi;
        } catch (Exception e) {
            log.error("更新爻辞失败: {}", yaoCi, e);
            return null;
        }
    }
    
    @Override
    public boolean deleteYaoCi(Integer id) {
        try {
            int result = yaoCiMapper.deleteById(id);
            return result > 0;
        } catch (Exception e) {
            log.error("删除爻辞失败: {}", id, e);
            return false;
        }
    }
}